﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

using ApocDev.TownsApi.XmlFiles;

namespace ApocDev.TownsApi
{
    public static class Extensions
    {
        public static string CamelToSpaced(this string s)
        {
            StringBuilder sb = new StringBuilder();
            bool firstChar = true;
            foreach (var c in s)
            {
                // Append a space to the string, if it's not the first character.
                if (char.IsUpper(c) && !firstChar)
                    sb.Append(' ');

                sb.Append(c);
                firstChar = false;
            }
            return sb.ToString();
        }

        public static string CamelToXmlTag(this string s)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(char.ToLower(s[0]));
            for (int i = 1; i < s.Length; i++)
            {
                sb.Append(s[i]);
            }
            return sb.ToString();
        }

        public static void AddEx(this XContainer xml, string name, object value)
        {
            xml.Add(new XElement(name, value));
        }
    }

    public static class Xml
    {
        public static XElement AddIf<T>(string name, T value, T condition = default(T))
        {
            // Special handling for strings. Want null or whitespace. (null or "")
            if (value is string)
            {
                if (!string.IsNullOrWhiteSpace(value as string))
                    return new XElement(name, value);
                return null;
            }
            if (value is RandomRoll)
            {
                if(!(value as RandomRoll).IsZero)
                    return new XElement(name, (value as RandomRoll).StringValue);
                return null;
            }

            // Basically, if its the "default value" then just give back a null.
            // Otherwise, we'll create an element for the non-default.
            if (value.Equals(condition))
                return null;
            return new XElement(name, value);
        }

        public static XElement AddIf(string name, Func<object> value, bool condition)
        {
            if(condition)
                return new XElement(name, value());
            return null;
        }

        public static XElement AddCollection(string name, IEnumerable<IChangedXml> xmlParts, bool dirtyCheck = false)
        {
            XElement root = new XElement(name);
            foreach (var changedXml in xmlParts)
            {
                if (dirtyCheck)
                {
                    if (changedXml.IsDirty)
                        root.Add(changedXml.SaveDirty());
                }
                else
                {
                    root.Add(changedXml.Save());
                }
            }
            return root;
        }
    }
}
